// pages/health/recommendation/recommendation.js
import { reqRecipeListData } from '../../../api/index/recipeList'
import { reqHotListData } from '../../../api/index/hotList'

Page({
  data: {
    // 健康参数
    healthParams: {},
    
    // 推荐结果
    recommendations: {
      breakfast: [],
      lunch: [],
      dinner: [],
      snack: []
    },
    
    // 推荐理由
    recommendationReasons: [],
    
    // 营养建议
    nutritionAdvice: '',
    
    // 加载状态
    loading: true,
    
    // 当前选中的餐次
    selectedMeal: 'breakfast',
    
    // 餐次选项
    mealOptions: [
      { key: 'breakfast', name: '早餐', icon: '🌅' },
      { key: 'lunch', name: '午餐', icon: '☀️' },
      { key: 'dinner', name: '晚餐', icon: '🌙' },
      { key: 'snack', name: '加餐', icon: '🍎' }
    ]
  },

  onLoad(options) {
    if (options.params) {
      try {
        const healthParams = JSON.parse(decodeURIComponent(options.params));
        this.setData({ healthParams });
        this.generateRecommendations();
      } catch (e) {
        console.error('解析健康参数失败:', e);
        wx.showToast({
          title: '参数错误',
          icon: 'none'
        });
      }
    }
  },

  // 生成个性化推荐
  async generateRecommendations() {
    this.setData({ loading: true });
    
    try {
      // 获取基础食谱数据
      const [recipeListData, hotListData] = await Promise.all([
        reqRecipeListData(1, 50),
        reqHotListData()
      ]);
      
      const allRecipes = [
        ...recipeListData.data.list,
        ...hotListData.data.list
      ];
      
      // 基于健康数据生成推荐
      const recommendations = this.calculatePersonalizedRecommendations(allRecipes);
      
      this.setData({
        recommendations,
        loading: false
      });
      
      // 生成推荐理由和营养建议
      this.generateAdvice();
      
    } catch (error) {
      console.error('获取推荐数据失败:', error);
      this.setData({ loading: false });
      wx.showToast({
        title: '获取推荐失败',
        icon: 'none'
      });
    }
  },

  // 计算个性化推荐
  calculatePersonalizedRecommendations(recipes) {
    const { healthParams } = this.data;
    const recommendations = {
      breakfast: [],
      lunch: [],
      dinner: [],
      snack: []
    };

    // 根据健康指标筛选和排序食谱
    const filteredRecipes = this.filterRecipesByHealth(recipes);
    
    // 按餐次分配食谱
    recommendations.breakfast = this.selectRecipesForMeal(filteredRecipes, 'breakfast', 3);
    recommendations.lunch = this.selectRecipesForMeal(filteredRecipes, 'lunch', 4);
    recommendations.dinner = this.selectRecipesForMeal(filteredRecipes, 'dinner', 3);
    recommendations.snack = this.selectRecipesForMeal(filteredRecipes, 'snack', 2);

    return recommendations;
  },

  // 根据健康指标筛选食谱
  filterRecipesByHealth(recipes) {
    const { healthParams } = this.data;
    const { bmi, bmiStatus, bodyFatRate, bloodPressure, bloodSugar } = healthParams;

    return recipes.map(recipe => {
      let score = 0;
      let reasons = [];

      // BMI相关推荐
      if (bmiStatus === '偏瘦') {
        // 推荐高热量、高蛋白食物
        if (this.isHighCalorieRecipe(recipe)) {
          score += 3;
          reasons.push('适合增重');
        }
        if (this.isHighProteinRecipe(recipe)) {
          score += 2;
          reasons.push('富含蛋白质');
        }
      } else if (bmiStatus === '偏胖' || bmiStatus === '肥胖') {
        // 推荐低热量、高纤维食物
        if (this.isLowCalorieRecipe(recipe)) {
          score += 3;
          reasons.push('低热量');
        }
        if (this.isHighFiberRecipe(recipe)) {
          score += 2;
          reasons.push('高纤维');
        }
      }

      // 体脂率相关推荐
      if (bodyFatRate > 30) {
        // 推荐减脂食物
        if (this.isFatBurningRecipe(recipe)) {
          score += 2;
          reasons.push('有助于减脂');
        }
      }

      // 血压相关推荐
      if (bloodPressure.systolic >= 140 || bloodPressure.diastolic >= 90) {
        // 推荐低钠食物
        if (this.isLowSodiumRecipe(recipe)) {
          score += 2;
          reasons.push('低钠');
        }
        if (this.isHeartHealthyRecipe(recipe)) {
          score += 2;
          reasons.push('有益心脏');
        }
      }

      // 血糖相关推荐
      if (bloodSugar.fasting >= 7.0 || bloodSugar.postprandial >= 11.1) {
        // 推荐低糖食物
        if (this.isLowSugarRecipe(recipe)) {
          score += 3;
          reasons.push('低糖');
        }
        if (this.isDiabetesFriendlyRecipe(recipe)) {
          score += 2;
          reasons.push('适合糖尿病患者');
        }
      }

      return {
        ...recipe,
        healthScore: score,
        healthReasons: reasons
      };
    }).filter(recipe => recipe.healthScore > 0)
      .sort((a, b) => b.healthScore - a.healthScore);
  },

  // 为特定餐次选择食谱
  selectRecipesForMeal(filteredRecipes, mealType, count) {
    const mealRecipes = filteredRecipes.filter(recipe => {
      // 根据食谱名称或分类判断适合的餐次
      const title = recipe.title.toLowerCase();
      const category = recipe.category_name || '';
      
      switch (mealType) {
        case 'breakfast':
          return title.includes('粥') || title.includes('豆浆') || 
                 title.includes('包子') || title.includes('面包') ||
                 category.includes('早餐') || category.includes('粥品');
        case 'lunch':
          return title.includes('米饭') || title.includes('面条') ||
                 title.includes('炒菜') || title.includes('汤') ||
                 category.includes('主食') || category.includes('家常菜');
        case 'dinner':
          return title.includes('汤') || title.includes('炖') ||
                 title.includes('蒸') || title.includes('煮') ||
                 category.includes('汤品') || category.includes('炖品');
        case 'snack':
          return title.includes('水果') || title.includes('坚果') ||
                 title.includes('酸奶') || title.includes('沙拉') ||
                 category.includes('甜品') || category.includes('沙拉');
        default:
          return true;
      }
    });

    return mealRecipes.slice(0, count);
  },

  // 食谱特征判断方法
  isHighCalorieRecipe(recipe) {
    const title = recipe.title.toLowerCase();
    return title.includes('肉') || title.includes('蛋') || 
           title.includes('奶') || title.includes('坚果');
  },

  isHighProteinRecipe(recipe) {
    const title = recipe.title.toLowerCase();
    return title.includes('鸡') || title.includes('鱼') || 
           title.includes('豆') || title.includes('蛋');
  },

  isLowCalorieRecipe(recipe) {
    const title = recipe.title.toLowerCase();
    return title.includes('蔬菜') || title.includes('水果') || 
           title.includes('沙拉') || title.includes('蒸');
  },

  isHighFiberRecipe(recipe) {
    const title = recipe.title.toLowerCase();
    return title.includes('蔬菜') || title.includes('全麦') || 
           title.includes('燕麦') || title.includes('豆类');
  },

  isFatBurningRecipe(recipe) {
    const title = recipe.title.toLowerCase();
    return title.includes('绿茶') || title.includes('辣椒') || 
           title.includes('柠檬') || title.includes('姜');
  },

  isLowSodiumRecipe(recipe) {
    const title = recipe.title.toLowerCase();
    return !title.includes('咸') && !title.includes('腌') && 
           !title.includes('酱') && !title.includes('盐');
  },

  isHeartHealthyRecipe(recipe) {
    const title = recipe.title.toLowerCase();
    return title.includes('鱼') || title.includes('橄榄油') || 
           title.includes('坚果') || title.includes('燕麦');
  },

  isLowSugarRecipe(recipe) {
    const title = recipe.title.toLowerCase();
    return !title.includes('糖') && !title.includes('甜') && 
           !title.includes('蜜') && !title.includes('糖浆');
  },

  isDiabetesFriendlyRecipe(recipe) {
    const title = recipe.title.toLowerCase();
    return title.includes('全麦') || title.includes('燕麦') || 
           title.includes('蔬菜') || title.includes('豆类');
  },

  // 生成推荐理由和营养建议
  generateAdvice() {
    const { healthParams } = this.data;
    const reasons = [];
    let advice = '';

    // BMI建议
    if (healthParams.bmiStatus === '偏瘦') {
      reasons.push('您的BMI偏低，建议增加营养密度高的食物');
      advice += '建议增加优质蛋白质和健康脂肪的摄入，如鱼类、坚果、橄榄油等。';
    } else if (healthParams.bmiStatus === '偏胖' || healthParams.bmiStatus === '肥胖') {
      reasons.push('您的BMI偏高，建议控制热量摄入');
      advice += '建议选择低热量、高纤维的食物，控制碳水化合物摄入，增加蔬菜和蛋白质比例。';
    }

    // 体脂率建议
    if (healthParams.bodyFatRate > 30) {
      reasons.push('体脂率偏高，存在内脏脂肪堆积风险');
      advice += '建议增加有氧运动，选择富含不饱和脂肪酸的食物，如深海鱼类、坚果等。';
    }

    // 血压建议
    if (healthParams.bloodPressure.systolic >= 140 || healthParams.bloodPressure.diastolic >= 90) {
      reasons.push('血压偏高，存在心血管疾病风险');
      advice += '建议低钠饮食，增加钾的摄入，选择富含Omega-3脂肪酸的食物，如深海鱼类。';
    }

    // 血糖建议
    if (healthParams.bloodSugar.fasting >= 7.0 || healthParams.bloodSugar.postprandial >= 11.1) {
      reasons.push('血糖偏高，建议咨询医生');
      advice += '建议选择低升糖指数食物，控制碳水化合物摄入，增加膳食纤维，定时定量进餐。';
    }

    this.setData({
      recommendationReasons: reasons,
      nutritionAdvice: advice
    });
  },

  // 切换餐次
  switchMeal(e) {
    const mealType = e.currentTarget.dataset.meal;
    this.setData({ selectedMeal: mealType });
  },

  // 查看食谱详情
  viewRecipeDetail(e) {
    const recipeId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/index/detail/detail?id=${recipeId}`
    });
  },

  // 收藏食谱
  favoriteRecipe(e) {
    const recipeId = e.currentTarget.dataset.id;
    // 这里可以调用收藏API
    wx.showToast({
      title: '已收藏',
      icon: 'success'
    });
  },

  // 重新生成推荐
  regenerateRecommendations() {
    this.generateRecommendations();
  }
})
